#include "mergedexportmanager.h"
#include "singlefileexporttask.h"
#include "unifiedpagerenderer.h"
#include "watermark.h"
#include "configmanager.h"
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QStandardPaths>
#include <QtCore/QDateTime>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QStringList>
#include <QtCore/QMarginsF>
#include <QtCore/QThread>
#include <QtCore/QMetaObject>
#include <QtWidgets/QApplication>
#include <QtGui/QPdfWriter>
#include <QtGui/QPainter>
#include <QtGui/QPageSize>
#include <QtPdf/QPdfDocument>
#include <memory>
#include <vector>
#include <cpp/poppler-document.h>
#include <cpp/poppler-page.h>
#include <fstream>

// 静态成员初始化
QAtomicInt MergedExportManager::s_globalExportState(static_cast<int>(GlobalExportState::Idle));
QAtomicInt MergedExportManager::s_exportThreadId(0);
QDateTime MergedExportManager::s_exportStartTime;

MergedExportManager::MergedExportManager(QObject *parent)
    : QObject(parent)
    , m_renderer(nullptr)
    // m_isExporting 已移除，统一使用全局状态
    , m_totalFiles(0)
    , m_completedFiles(0)
    , m_exportMode(SinglePDF)
    , m_exportThread(nullptr)
    , m_cancelRequested(0)
    , m_exportToken(0)  // KISS增强：初始化令牌
{
    // 初始化线程池
    m_threadPool = new QThreadPool(this);

    // 根据CPU核心数设置并发线程数
    int maxThreads = QThread::idealThreadCount();
    if (maxThreads > 1) {
        m_threadPool->setMaxThreadCount(maxThreads - 1); // 保留一个核心给UI
    } else {
        m_threadPool->setMaxThreadCount(1);
    }

    // 进度检查定时器
    m_progressTimer = new QTimer(this);
    m_progressTimer->setInterval(500); // 每500ms检查一次进度
    connect(m_progressTimer, &QTimer::timeout, this, &MergedExportManager::checkExportProgress);

    // ✅ 修复：移除不再需要的线程退出确认信号（改用单一定时器）

    // 🎯 方案A重构：确保启动时状态为Idle
    s_globalExportState.storeRelease(static_cast<int>(GlobalExportState::Idle));
}

MergedExportManager::~MergedExportManager()
{
    stopExport();
    cleanupTempFiles();
}

void MergedExportManager::setUnifiedRenderer(UnifiedPageRenderer* renderer)
{
    m_renderer = renderer;
}

// ✅ 清理：移除废弃的多阶段进度计算方法
// 当前导出流程不再使用三阶段系统

void MergedExportManager::startExport(const QList<UnifiedFileInfo>& files,
                                      const ProcessingSettings& settings,
                                      const QString& outputPath,
                                      ExportMode mode)
{

    // ✅ 修复：使用原子操作testAndSet避免竞态条件
    // 原子地检查并切换状态：只有当前状态为Idle时才能切换到Exporting
    int expected = static_cast<int>(::GlobalExportState::Idle);
    int desired = static_cast<int>(::GlobalExportState::Exporting);
    
    if (!s_globalExportState.testAndSetOrdered(expected, desired)) {
        // 状态切换失败，说明当前不是Idle状态
        ::GlobalExportState currentState = static_cast<::GlobalExportState>(s_globalExportState.loadAcquire());
        
        QString errorMsg;
        switch (currentState) {
            case ::GlobalExportState::CollectingPages:
            case ::GlobalExportState::Exporting:
                errorMsg = "已有导出任务正在进行，请先取消";
                break;
            case ::GlobalExportState::Cancelling:
                errorMsg = "正在取消导出，请稍后再试";
                break;
            case ::GlobalExportState::Cleaning:
                errorMsg = "正在清理资源，请稍后再试";
                break;
            default:
                errorMsg = "系统繁忙，请稍候";
                break;
        }
        qWarning() << "[MergedExportManager] ❌ 拒绝启动：" << errorMsg;
        emit exportFailed(errorMsg);
        return;
    }
    
    // 原子切换成功！设置相关元数据
    s_exportThreadId.storeRelease(reinterpret_cast<quintptr>(QThread::currentThreadId()));
    s_exportStartTime = QDateTime::currentDateTime();
    emit globalStateChanged(static_cast<int>(::GlobalExportState::Exporting));

    // ✅ 修复：移除死代码（状态已设置为Exporting，检查Idle永远为true）
    
    if (!m_renderer) {
        emit exportFailed("统一渲染器未设置");
        return;
    }

    if (files.isEmpty()) {
        emit exportFailed("没有文件需要导出");
        return;
    }

    // KISS重构：启动前清理残留状态（幂等性保证）
    cleanupExportState();
    
    // KISS增强：生成新导出令牌（防止旧线程干扰）
    quint64 newToken = generateToken();
    m_exportToken.storeRelease(newToken);

    m_files = files;
    m_settings = settings;
    m_outputPath = outputPath;
    m_exportMode = mode;


    initializeExport();

}

void MergedExportManager::startExportFromPages(const QList<QImage>& pages,
                                               const ProcessingSettings& settings,
                                               const QString& outputPath)
{

    // ✅ 修复：使用原子操作，允许Idle或CollectingPages状态切换到Exporting
    // 使用循环尝试原子切换（支持从Idle或CollectingPages切换）
    bool stateChangeSucceeded = false;
    int maxRetries = 3;
    
    for (int retry = 0; retry < maxRetries && !stateChangeSucceeded; ++retry) {
        ::GlobalExportState currentState = getGlobalExportState();
        
        if (currentState == ::GlobalExportState::Idle || 
            currentState == ::GlobalExportState::CollectingPages) {
            // 尝试原子切换
            int expected = static_cast<int>(currentState);
            int desired = static_cast<int>(::GlobalExportState::Exporting);
            
            if (s_globalExportState.testAndSetOrdered(expected, desired)) {
                stateChangeSucceeded = true;
                break;
            }
            // 切换失败，说明状态被其他线程改变了，重试
        } else {
            // 其他状态，拒绝启动
            QString errorMsg;
            switch (currentState) {
                case ::GlobalExportState::Exporting:
                    errorMsg = "已有导出任务在运行，请稍候";
                    break;
                case ::GlobalExportState::Cancelling:
                    errorMsg = "正在取消导出，请稍后再试";
                    break;
                case ::GlobalExportState::Cleaning:
                    errorMsg = "正在清理资源，请稍后再试";
                    break;
                default:
                    errorMsg = "系统繁忙，请稍候";
                    break;
            }
            qWarning() << "[MergedExportManager] ❌ startExportFromPages() 拒绝启动：" << errorMsg;
            emit exportFailed(errorMsg);
            return;
        }
    }
    
    if (!stateChangeSucceeded) {
        qWarning() << "[MergedExportManager] ❌ 状态切换失败，重试" << maxRetries << "次后放弃";
        emit exportFailed("状态竞争，导出启动失败，请重试");
        return;
    }

    if (pages.isEmpty()) {
        // 状态切换成功但页面为空，需要回退状态
        s_globalExportState.storeRelease(static_cast<int>(::GlobalExportState::Idle));
        emit globalStateChanged(static_cast<int>(::GlobalExportState::Idle));
        emit exportFailed("没有页面需要导出");
        return;
    }
    
    // KISS增强：生成新导出令牌（防止旧线程干扰）
    quint64 newToken = generateToken();
    m_exportToken.storeRelease(newToken);

    m_pages = pages; // 保存页面数据
    m_settings = settings;
    m_outputPath = outputPath;
    m_exportMode = SinglePDF;

    // 设置相关元数据
    s_exportThreadId.storeRelease(reinterpret_cast<quintptr>(QThread::currentThreadId()));
    s_exportStartTime = QDateTime::currentDateTime();
    emit globalStateChanged(static_cast<int>(::GlobalExportState::Exporting));

    // ✅ 清理：移除废弃的分阶段进度信号

    // 状态由全局状态管理，无需设置实例状态;
    m_totalFiles = 1; // 直接页面导出视为单个文件
    m_completedFiles = 0;

    // 发送导出开始信号
    emit exportStarted(1, outputPath); // 显示为1个文件导出

    // 启动异步导出任务
    startAsyncPageExport();
}

void MergedExportManager::startAsyncPageExport()
{
    // 防止重复启动（修复多线程并发问题）
    if (m_exportThread && m_exportThread->isRunning()) {
        qWarning() << "[MergedExportManager] 导出线程已在运行，忽略重复启动请求";
        return;
    }

    // 🔑 KISS增强：拷贝数据到线程（完全隔离，避免数据竞争）
    QList<QImage> pagesCopy = m_pages;  // 深拷贝图像数据
    QString outputPathCopy = m_outputPath;  // 拷贝路径
    ProcessingSettings settingsCopy = m_settings;  // 拷贝配置
    quint64 myToken = m_exportToken.loadAcquire();  // 获取当前令牌
    

    // 创建异步导出任务
    m_exportThread = new QThread(this);
    QObject* exportWorker = new QObject();
    exportWorker->moveToThread(m_exportThread);

    // 🔑 连接线程信号 - 按值捕获（线程安全）
    connect(m_exportThread, &QThread::started, 
            [this, exportWorker, pagesCopy, outputPathCopy, settingsCopy, myToken]() {
        
        // 使用线程独有的数据副本
        bool success = exportPagesToPDFIsolated(
            pagesCopy,      // 线程独有副本
            outputPathCopy, // 线程独有副本
            settingsCopy,   // 线程独有副本
            myToken         // 线程的令牌
        );
        
        // 发送结果信号
        if (success) {
            QMetaObject::invokeMethod(this, "onAsyncPageExportCompleted", 
                                    Qt::QueuedConnection);
        } else {
            QMetaObject::invokeMethod(this, "exportFailed", 
                                    Qt::QueuedConnection,
                                    Q_ARG(QString, "页面合并为PDF失败"));
        }
        
        exportWorker->deleteLater();
    });
    
    connect(m_exportThread, &QThread::finished, [this]() {
        if (m_exportThread) {
            m_exportThread->deleteLater();
            m_exportThread = nullptr;
        }
    });

    // 启动线程
    m_exportThread->start();
}

void MergedExportManager::onAsyncPageExportCompleted()
{
    // 调用finalizeExport来正确重置状态
    finalizeExport();
}

void MergedExportManager::stopExport()
{
    
    // 1. 幂等性检查 - 立即返回如果已经是Idle或Cancelling
    GlobalExportState current = getGlobalExportState();
    if (current == GlobalExportState::Idle) {
        return;
    }
    
    if (current == GlobalExportState::Cancelling) {
        return;
    }
    
    // 2. 原子切换状态到Cancelling
    int expected = static_cast<int>(current);
    int desired = static_cast<int>(GlobalExportState::Cancelling);
    
    if (!s_globalExportState.testAndSetOrdered(expected, desired)) {
        return;
    }
    
    emit globalStateChanged(static_cast<int>(GlobalExportState::Cancelling));
    
    // 3. 设置取消标志（只一次）
    m_cancelRequested.storeRelease(1);
    
    // 4. 停止定时器
    if (m_progressTimer) {
        m_progressTimer->stop();
    }
    
    // 5. 快速清理线程池（不等待）
    if (m_threadPool) {
        m_threadPool->clear();
    }
    
    // 6. 清理状态变量
    cleanupExportState();
    
    // 7. 等待线程退出（关键修复）
    if (m_exportThread && m_exportThread->isRunning()) {
        if (!m_exportThread->wait(3000)) {
            qWarning() << "[MergedExportManager] Thread didn't exit in 3s, forcing cleanup";
        } else {
        }
    }

    // 8. 现在可以安全重置状态
    s_globalExportState.storeRelease(static_cast<int>(GlobalExportState::Idle));
    s_exportThreadId.storeRelease(0);


    // 9. 发出信号
    emit exportCancelled();
    emit exportCancelledByUser();
    emit globalStateChanged(static_cast<int>(GlobalExportState::Idle));

}

// 新增：清理方法（提取重复代码）
void MergedExportManager::cleanupExportState()
{
    
    m_totalFiles = 0;
    m_completedFiles = 0;
    m_exportResults.clear();
    m_files.clear();
    m_pages.clear();
    m_outputPath.clear();
    
    // KISS增强：不重置取消标志（令牌机制会自然失效旧线程）
    // m_cancelRequested.storeRelease(0);  // ← 删除重置
    
    cleanupTempFiles();
}

// KISS增强：生成唯一导出令牌
quint64 MergedExportManager::generateToken() const
{
    static QAtomicInteger<quint64> s_tokenCounter(0);
    
    // 时间戳（毫秒）+ 计数器 = 唯一令牌
    quint64 timestamp = QDateTime::currentMSecsSinceEpoch();
    quint64 counter = s_tokenCounter.fetchAndAddOrdered(1);
    
    return (timestamp << 32) | (counter & 0xFFFFFFFF);
}

// KISS增强：检查令牌是否有效
bool MergedExportManager::isValidToken(quint64 token) const
{
    return token == m_exportToken.loadAcquire();
}

// ✅ 修复：移除onThreadExited方法（不再需要，改用单一定时器）

// 状态查询方法实现
GlobalExportState MergedExportManager::getGlobalExportState()
{
    return static_cast<GlobalExportState>(s_globalExportState.loadAcquire());
}

bool MergedExportManager::isGloballyExporting()
{
    GlobalExportState state = getGlobalExportState();
    return state == GlobalExportState::CollectingPages || state == GlobalExportState::Exporting || state == GlobalExportState::Cancelling || state == GlobalExportState::Cleaning;
}

bool MergedExportManager::canStartNewExport()
{
    return getGlobalExportState() == GlobalExportState::Idle;
}

QString MergedExportManager::getStateDescription()
{
    GlobalExportState state = getGlobalExportState();
    switch (state) {
        case GlobalExportState::Idle:
            return "空闲状态";
        case GlobalExportState::Exporting:
            return "导出中";
        case GlobalExportState::Cancelling:
            return "正在取消...";
        case GlobalExportState::Cleaning:
            return "正在清理资源...";
        default:
            return "未知状态";
    }
}

void MergedExportManager::setGlobalExportState(int state)
{
    s_globalExportState.storeRelease(state);
}

// ✅ 清理：移除setCollectingPagesState()方法（收集在MainWindow中完成）

// ✅ 清理：移除updateCollectionProgress()方法（收集在MainWindow中完成）

int MergedExportManager::getCompletedFileCount() const
{
    QMutexLocker locker(&m_resultsMutex);
    int completed = 0;
    for (const auto& result : m_exportResults) {
        if (result.status == ExportTaskStatus::Completed) {
            completed++;
        }
    }
    return completed;
}

void MergedExportManager::onFileExportCompleted(const QString& filePath)
{
    QMutexLocker locker(&m_resultsMutex);
    if (m_exportResults.contains(filePath)) {
        m_exportResults[filePath].status = ExportTaskStatus::Completed;
        m_completedFiles++;


        emit fileProgressUpdated(filePath, 100, ExportTaskStatus::Completed);
    }
}

void MergedExportManager::onFileExportFailed(const QString& filePath, const QString& error)
{
    QMutexLocker locker(&m_resultsMutex);
    if (m_exportResults.contains(filePath)) {
        m_exportResults[filePath].status = ExportTaskStatus::Failed;
        m_exportResults[filePath].errorMessage = error;


        emit fileProgressUpdated(filePath, 0, ExportTaskStatus::Failed);
    }
}

void MergedExportManager::checkExportProgress()
{
    // 双重状态检查，确保不在取消状态下发送进度信号
    if (getGlobalExportState() == GlobalExportState::Idle || m_cancelRequested.loadAcquire()) {
        return;
    }

    int completed = getCompletedFileCount();


    // ✅ 清理：直接发送简单进度信号
    emit progressUpdated(completed, m_totalFiles, QString(""));

    // 心跳监控已移除

    // 检查是否所有任务都完成
    bool allCompleted = (completed == m_totalFiles);
    bool hasFailed = false;


    {
        QMutexLocker locker(&m_resultsMutex);
        for (const auto& result : m_exportResults) {
            if (result.status == ExportTaskStatus::Failed) {
                hasFailed = true;
                break;
            }
        }
    }

    if (allCompleted || hasFailed) {
        m_progressTimer->stop();

        if (hasFailed) {
            // 收集错误信息
            QStringList errors;
            {
                QMutexLocker locker(&m_resultsMutex);
                for (const auto& result : m_exportResults) {
                    if (result.status == ExportTaskStatus::Failed) {
                        errors << QString("%1: %2").arg(result.filePath).arg(result.errorMessage);
                    }
                }
            }

            cleanupTempFiles();
            emit exportFailed(QString("部分文件导出失败：\n%1").arg(errors.join("\n")));
            return;
        }

        // 所有文件都成功导出
        if (m_exportMode == SinglePDF) {
            // 需要合并PDF
            mergeCompletedFiles();
        } else {
            // 多PDF模式，直接完成
            finalizeExport();
        }
    }
}

void MergedExportManager::initializeExport()
{

    // 状态由全局状态管理，无需设置实例状态;
    m_totalFiles = m_files.size();
    m_completedFiles = 0;

    // 清理之前的结果
    m_exportResults.clear();
    cleanupTempFiles();


    // 发送导出开始信号（增加状态检查）
    if (getGlobalExportState() != GlobalExportState::Idle && !m_cancelRequested.loadAcquire()) {
        emit exportStarted(m_totalFiles, m_outputPath);
    } else {
    }

    // 计算页码
    calculatePageNumbers();

    // 开始并行导出
    startParallelExport();

    // 开始进度监控
    m_progressTimer->start();

    // 心跳监控已移除

}

void MergedExportManager::calculatePageNumbers()
{
    int currentPageNumber = m_settings.pageNumber.startNumber;

    for (const UnifiedFileInfo& fileInfo : m_files) {
        FileExportResult result;
        result.filePath = fileInfo.filePath;
        result.startPageNumber = currentPageNumber;
        result.pageCount = fileInfo.pageCount;
        result.status = ExportTaskStatus::Pending;

        // 生成临时PDF路径
        result.tempPdfPath = generateTempFilePath(fileInfo.filePath);

        m_exportResults[fileInfo.filePath] = result;

        currentPageNumber += fileInfo.pageCount;

    }
}

void MergedExportManager::startParallelExport()
{
    for (const UnifiedFileInfo& fileInfo : m_files) {
        if (getGlobalExportState() == GlobalExportState::Idle) break;

        const FileExportResult& result = m_exportResults[fileInfo.filePath];

        // 创建单文件导出任务
        SingleFileExportTask* task = new SingleFileExportTask(
            fileInfo,
            m_settings,
            result.tempPdfPath,
            result.startPageNumber,
            m_renderer,
            this
        );

        // 连接信号
        connect(task, &SingleFileExportTask::exportCompleted,
                this, &MergedExportManager::onFileExportCompleted);
        connect(task, &SingleFileExportTask::exportFailed,
                this, &MergedExportManager::onFileExportFailed);

        // 标记为处理中
        {
            QMutexLocker locker(&m_resultsMutex);
            m_exportResults[fileInfo.filePath].status = ExportTaskStatus::Processing;
        }

        emit fileProgressUpdated(fileInfo.filePath, 0, ExportTaskStatus::Processing);

        // 提交到线程池
        m_threadPool->start(task);
    }

}

void MergedExportManager::mergeCompletedFiles()
{
    // ✅ 清理：直接发送简单进度信号
    emit progressUpdated(m_totalFiles, m_totalFiles, "正在合并PDF文件...");

    // 收集所有成功导出的临时PDF文件
    QStringList tempPdfPaths;
    {
        QMutexLocker locker(&m_resultsMutex);
        for (const UnifiedFileInfo& fileInfo : m_files) {
            const FileExportResult& result = m_exportResults[fileInfo.filePath];
            if (result.status == ExportTaskStatus::Completed) {
                tempPdfPaths << result.tempPdfPath;
            }
        }
    }

    if (tempPdfPaths.isEmpty()) {
        emit exportFailed("没有成功导出的PDF文件可以合并");
        return;
    }

    // 执行PDF合并
    bool success = mergePDFs(tempPdfPaths, m_outputPath);

    if (success) {
        finalizeExport();
    } else {
        emit exportFailed("PDF合并失败");
    }
}

bool MergedExportManager::mergePDFs(const QStringList& inputPaths, const QString& outputPath)
{

    if (inputPaths.isEmpty()) {
        return false;
    }

    // 使用Qt内置功能进行PDF合并

    // 确保目标目录存在
    QFileInfo outputInfo(outputPath);
    QDir outputDir = outputInfo.absoluteDir();
    if (!outputDir.exists()) {
        if (!outputDir.mkpath(".")) {
            return false;
        }
    }

    // 如果目标文件已存在，删除它
    if (QFile::exists(outputPath)) {
        QFile::remove(outputPath);
    }

    try {
        // 创建输出PDF写入器
        QPdfWriter writer(outputPath);
        writer.setPageSize(QPageSize::A4);
        writer.setPageMargins(QMarginsF(0, 0, 0, 0));
        // Martin Fowler重构：Replace Magic Number - 使用配置驱动的DPI
        writer.setResolution(m_settings.standardDPI);

        QPainter painter(&writer);
        if (!painter.isActive()) {
            return false;
        }

        bool firstPage = true;
        int totalPagesProcessed = 0;

        // 遍历每个输入PDF文件
        for (int fileIndex = 0; fileIndex < inputPaths.size(); ++fileIndex) {
            const QString& inputPath = inputPaths[fileIndex];

            // 加载PDF文档
            QPdfDocument document;
            QPdfDocument::Error loadResult = document.load(inputPath);

            if (loadResult != QPdfDocument::Error::None) {
                continue;
            }

            int pageCount = document.pageCount();

            // 遍历文档的每一页
            for (int pageIndex = 0; pageIndex < pageCount; ++pageIndex) {
                if (!firstPage) {
                    writer.newPage();
                } else {
                    firstPage = false;
                }

                // Martin Fowler重构：Replace Magic Number - 使用配置驱动的DPI
                QSizeF pageSize = document.pagePointSize(pageIndex);
                qreal dpi = m_settings.standardDPI;
                QSize renderSize = QSize(
                    static_cast<int>(pageSize.width() * dpi / 72.0),
                    static_cast<int>(pageSize.height() * dpi / 72.0)
                );

                QImage pageImage = document.render(pageIndex, renderSize);

                if (pageImage.isNull()) {
                    continue;
                }

                // Martin Fowler重构：Replace Method with Method Object - 使用统一渲染器
                if (m_renderer) {
                    // 计算全局页码（总页数计算需要遍历所有文件）
                    int globalPageNumber = calculateGlobalPageNumber(fileIndex, pageIndex, inputPaths);

                    // 设置页面内容到统一渲染器
                    m_renderer->setPageContent(pageImage);
                    m_renderer->setRenderSettings(m_settings);

                    // 使用统一渲染器进行PDF渲染（包含页码、边距、DPI增强等特性）
                    m_renderer->renderToPDF(&writer, &painter, globalPageNumber);

                } else {
                    // Martin Fowler重构：Introduce Guard Clause - 兜底逻辑
                    QRect pageRect = painter.viewport();
                    QSize scaledSize = pageImage.size().scaled(pageRect.size(), Qt::KeepAspectRatio);
                    QRect targetRect(0, 0, scaledSize.width(), scaledSize.height());
                    targetRect.moveCenter(pageRect.center());
                    painter.drawImage(targetRect, pageImage);
                }

                totalPagesProcessed++;
            }

        }

        painter.end();

        if (totalPagesProcessed > 0) {
            return true;
        } else {
            return false;
        }

    } catch (const std::exception& e) {
        return false;
    } catch (...) {
        return false;
    }
}

// Martin Fowler重构：Extract Method - 全局页码计算辅助方法
int MergedExportManager::calculateGlobalPageNumber(int fileIndex, int pageIndex, const QStringList& inputPaths) const
{
    int globalPageNumber = 1; // 全局页码从1开始

    // 累计前面所有文件的页数
    for (int i = 0; i < fileIndex; ++i) {
        QPdfDocument doc;
        if (doc.load(inputPaths[i]) == QPdfDocument::Error::None) {
            globalPageNumber += doc.pageCount();
        }
    }

    // 加上当前文件内的页面偏移
    globalPageNumber += pageIndex;

    return globalPageNumber;
}

bool MergedExportManager::exportPagesToPDF(const QList<QImage>& pages, const QString& outputPath)
{
    // 兼容方法：获取当前设置和令牌，调用隔离方法
    quint64 myToken = m_exportToken.loadAcquire();
    return exportPagesToPDFIsolated(pages, outputPath, m_settings, myToken);
}

// 🔑 KISS增强：完全隔离的导出方法（线程安全）
bool MergedExportManager::exportPagesToPDFIsolated(
    const QList<QImage>& pages,
    const QString& outputPath,
    const ProcessingSettings& settings,
    quint64 myToken
) {

    // 🔑 KISS增强：每页检查令牌和取消标志（快速退出）
    #define CHECK_TOKEN_AND_CANCEL() \
        do { \
            if (!isValidToken(myToken)) { \
                if (painter.isActive()) painter.end(); \
                return false; \
            } \
            if (m_cancelRequested.loadAcquire()) { \
                if (painter.isActive()) painter.end(); \
                return false; \
            } \
        } while(0)

    // 🔑 初始检查：令牌和取消标志
    if (!isValidToken(myToken)) {
        return false;
    }
    
    if (m_cancelRequested.loadAcquire()) {
        return false;
    }

    // 确保目标目录存在
    QFileInfo outputInfo(outputPath);
    QDir outputDir = outputInfo.absoluteDir();
    if (!outputDir.exists()) {
        if (!outputDir.mkpath(".")) {
            return false;
        }
    }

    // 如果目标文件已存在，删除它
    if (QFile::exists(outputPath)) {
        QFile::remove(outputPath);
    }

    try {
        // 创建PDF写入器（使用线程独有的settings副本）
        QPdfWriter writer(outputPath);
        writer.setPageSize(QPageSize::A4);
        writer.setPageMargins(QMarginsF(0, 0, 0, 0));
        writer.setResolution(settings.standardDPI);  // 使用参数

        // 标注元数据
        writer.setCreator("LongImageReader");
        writer.setTitle(QString("Merged Export (DPI=%1)").arg(settings.standardDPI));

        QPainter painter(&writer);
        if (!painter.isActive()) {
            return false;
        }

        // 🔑 KISS增强：每页都检查令牌和取消标志（快速退出）
        for (int i = 0; i < pages.size(); ++i) {
            // 每页开始前检查（令牌失效立即退出）
            CHECK_TOKEN_AND_CANCEL();

            if (i > 0) {
                writer.newPage();
            }

            const QImage& pageImage = pages[i];
            if (pageImage.isNull()) {
                continue;
            }

            // 🔑 KISS增强：直接绘制，不使用m_renderer（避免线程竞争）
            // 这确保了线程完全隔离，无共享资源冲突
            QRect pageRect = painter.viewport();
            QSize scaledSize = pageImage.size().scaled(pageRect.size(), Qt::KeepAspectRatio);
            QRect targetRect(0, 0, scaledSize.width(), scaledSize.height());
            targetRect.moveCenter(pageRect.center());
            painter.drawImage(targetRect, pageImage);

            // ✅ 优化：水印处理（仅外层检查取消）
            QString authToken = ConfigManager::getAuthToken();
            if (authToken.isEmpty()) {
                painter.save();

                // 设置水印字体和样式
                QFont watermarkFont("Microsoft YaHei", 36, QFont::Bold);
                painter.setFont(watermarkFont);
                painter.setPen(QColor(200, 200, 200, 120));
                painter.setRenderHint(QPainter::Antialiasing, true);

                // 计算水印位置（3x3网格布局）
                QRect pageRect = painter.viewport();
                int watermarkWidth = pageRect.width() / 3;
                int watermarkHeight = pageRect.height() / 3;
                QString watermarkText = "影谷长图处理大师";

                // 3x3网格水印（无内层取消检查，水印绘制很快）
                for (int row = 0; row < 3; ++row) {
                    for (int col = 0; col < 3; ++col) {
                        int x = col * watermarkWidth + watermarkWidth / 2;
                        int y = row * watermarkHeight + watermarkHeight / 2;

                        painter.save();
                        painter.translate(x, y);
                        painter.rotate(45);
                        
                        QRect textRect = painter.fontMetrics().boundingRect(watermarkText);
                        textRect.moveCenter(QPoint(0, 0));
                        painter.drawText(textRect, Qt::AlignCenter, watermarkText);
                        
                        painter.restore();
                    }
                }

                painter.restore();
            }

            // ✅ KISS增强：每10页发送一次进度更新，检查令牌
            if ((i + 1) % 10 == 0 || i == pages.size() - 1) {
                // 检查令牌是否有效（防止旧线程干扰）
                if (isValidToken(myToken) && !m_cancelRequested.loadAcquire()) {
                    QMetaObject::invokeMethod(this, "progressUpdated", Qt::QueuedConnection,
                                            Q_ARG(int, i + 1),
                                            Q_ARG(int, pages.size()),
                                            Q_ARG(QString, QString("")));
                } else if (!isValidToken(myToken)) {
                }
            }
        }

        painter.end();

        // ✅ KISS增强：发送最终进度信号前检查令牌
        if (isValidToken(myToken) && !m_cancelRequested.loadAcquire()) {
            m_completedFiles = 1;
            emit progressUpdated(m_completedFiles, m_totalFiles, QString(""));
        } else {
            if (!isValidToken(myToken)) {
            } else {
            }
        }

        
        // 清理宏定义
        #undef CHECK_TOKEN_AND_CANCEL
        
        return true;

    } catch (const std::exception& e) {
        qWarning() << "[Export] Exception:" << e.what();
        #undef CHECK_TOKEN_AND_CANCEL
        return false;
    } catch (...) {
        qWarning() << "[Export] Unknown exception";
        #undef CHECK_TOKEN_AND_CANCEL
        return false;
    }
}

void MergedExportManager::finalizeExport()
{

    // 状态由全局状态管理，无需设置实例状态;

    // 心跳监控已移除

    cleanupTempFiles();

    // 🎯 保存输出路径，用于发送信号（在清空之前）
    QString completedOutputPath = m_outputPath;

    // 重置所有导出状态变量，确保下次导出从干净状态开始
    m_totalFiles = 0;
    m_completedFiles = 0;
    m_exportResults.clear();
    m_files.clear();
    m_pages.clear();
    m_tempFiles.clear();
    m_outputPath.clear();


    // 发送完成信号
    emit exportCompleted(completedOutputPath);
    emit progressUpdated(0, 0, "");

    // 🎯 状态驱动设计：最后重置状态（确保所有信号处理完成后再重置）
    s_globalExportState.storeRelease(static_cast<int>(::GlobalExportState::Idle));
    s_exportThreadId.storeRelease(0);
    emit globalStateChanged(static_cast<int>(::GlobalExportState::Idle));

    // ✅ 修复：移除threadExited信号发送（已在阶段2移除该信号）

}

void MergedExportManager::cleanupTempFiles()
{
    for (const QString& tempFile : m_tempFiles) {
        if (QFile::exists(tempFile)) {
            QFile::remove(tempFile);
        }
    }
    m_tempFiles.clear();

    // 清理导出结果中的临时文件
    QMutexLocker locker(&m_resultsMutex);
    for (const auto& result : m_exportResults) {
        if (QFile::exists(result.tempPdfPath)) {
            QFile::remove(result.tempPdfPath);
        }
    }
}

QString MergedExportManager::generateTempFilePath(const QString& originalPath)
{
    QString tempDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
    QDir().mkpath(tempDir);

    QString baseName = QFileInfo(originalPath).baseName();
    QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss_zzz");
    QString tempFileName = QString("%1_%2.pdf").arg(baseName).arg(timestamp);

    QString tempPath = QDir(tempDir).absoluteFilePath(tempFileName);
    m_tempFiles << tempPath;

    return tempPath;
}

// 心跳和异常处理方法已移除 - 使用简化的导出流程
